<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { useGetWaitCheckStatementOrderService, useCheckStatementOrderService } from './services'
  import { ElMessage } from 'element-plus'
  import { ArrowLeftBold, ArrowRightBold, View } from '@element-plus/icons-vue'
  import HButton from '@/components/common/button/HButton.vue'
  import pdf from '@/assets/image/pdf.png'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    wordId: {
      type: String,
      required: true,
    },
    wordNo: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  // 使用获取待结单审核信息服务
  const {
    loading: getWaitCheckStatementOrderLoading,
    waitCheckStatementOrderInfo,
    get: getWaitCheckStatementOrderFn,
  } = useGetWaitCheckStatementOrderService

  // 使用待结单审核服务
  const {
    loading: checkStatementOrderLoading,
    form,
    reject,
    submit,
  } = useCheckStatementOrderService

  // 弹窗显示状态
  const modalVisible = ref(false)

  // 自定字段渲染数据(文本类)
  const customFieldRenderTextData = ref<Array<{ name: string; values: Array<string> }>>([])

  // 自定字段渲染数据(图片类)
  const customFieldRenderImageData = ref<Array<{ name: string; values: Array<string> }>>([])

  // 自定字段渲染数据(视频类)
  const customFieldRenderVideoData = ref<Array<{ name: string; values: Array<string> }>>([])

  // 自定字段渲染数据(附件类)
  const customFieldRenderFileData = ref<Array<{ name: string; values: Array<string> }>>([])

  // 自定字段渲染数据(评分)
  const customFieldRenderRateData = ref([])
  /**
   * 关闭事件
   */
  const onClose = () => {
    form.value.remark = ''
    modalVisible.value = false
    emits('update:modelValue', modalVisible.value)
  }

  /**
   * 驳回按钮点击事件
   */
  const onRejectBtnClick = async () => {
    const res = await reject(props.wordId)
    ElMessage({
      type: res.success ? 'success' : 'error',
      message: res.message,
    })
    if (res.success) {
      form.value.remark = ''
      onClose()
      emits('update')
    }
  }

  /**
   * 提交按钮点击事件
   */
  const onSubmitBtnClick = async () => {
    const res = await submit(props.wordId)
    ElMessage({
      type: res.success ? 'success' : 'error',
      message: res.message,
    })
    if (res.success) {
      form.value.remark = ''
      onClose()
      emits('update')
    }
  }

  // 视频预览弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 视频预览地址
  const videoPreviewUrls = ref<Array<string>>([])

  // 视频索引，用来标记当前的视频是第几个
  const videoPreviewIndex = ref(0)

  /**
   * 视频预览事件
   * @param {Array<string>} url - 视频预览地址
   * @param {number} index - 索引
   */
  const handlePreviewVideo = (url: Array<string>, index: number) => {
    videoPreviewModalVisible.value = true
    videoPreviewUrls.value = url
    videoPreviewIndex.value = index
  }

  /**
   * 视频预览弹窗关闭事件
   */
  const onCloseVideoPreviewModal = () => {
    videoPreviewModalVisible.value = false
    videoPreviewUrls.value = []
    videoPreviewIndex.value = 0
  }

  // 附件预览弹窗显示状态
  const filePreviewModalVisible = ref(false)

  // 附件预览地址
  const filePreviewUrls = ref<Array<string>>([])

  // 附件索引，用来标记当前的附件是第几个
  const filePreviewIndex = ref(0)

  /**
   * 附件预览事件
   */
  const handlePreviewFile = (index: number) => {
    filePreviewIndex.value = index
    filePreviewModalVisible.value = true
    customFieldRenderFileData.value.forEach((customFieldRenderFile) => {
      customFieldRenderFile.values.forEach((file) => {
        filePreviewUrls.value.push(file)
      })
    })
  }

  /**
   * 附件预览弹窗关闭事件
   */
  const onCloseFilePreviewModal = () => {
    filePreviewModalVisible.value = false
    filePreviewUrls.value = []
    filePreviewIndex.value = 0
  }

  watch(
    props,
    async (value) => {
      modalVisible.value = value.modelValue
      if (value.modelValue && value.wordId) {
        await getWaitCheckStatementOrderFn(value.wordId)
        form.value.id = waitCheckStatementOrderInfo.value.id
        customFieldRenderFileData.value = []
        customFieldRenderVideoData.value = []
        customFieldRenderTextData.value = []
        customFieldRenderImageData.value = []
        customFieldRenderRateData.value = []
        waitCheckStatementOrderInfo.value.finishOrderTemplates.forEach((finishOrderTemplate) => {
          finishOrderTemplate.fieldVals.forEach((fieldVal) => {
            if (fieldVal.type === 5) {
              customFieldRenderImageData.value.push({
                name: fieldVal.name,
                values: fieldVal.optVos
                  .filter((optVo) => !!optVo.optValue)
                  .map((optVo) => optVo.optValue),
              })
            }

            if ([1, 2, 3, 4].includes(fieldVal.type)) {
              customFieldRenderTextData.value.push({
                name: fieldVal.name,
                values: fieldVal.optVos.map((optVo) => optVo.optValue),
              })
            }

            if (fieldVal.type === 8) {
              customFieldRenderRateData.value.push({
                name: fieldVal.name,
                values: fieldVal.optVos.map((optVo) => optVo.optValue),
              })
            }

            if (fieldVal.type === 7) {
              customFieldRenderVideoData.value.push({
                name: fieldVal.name,
                values: fieldVal.optVos
                  .filter((optVo) => !!optVo.optValue)
                  .map((optVo) => optVo.optValue),
              })
            }

            if (fieldVal.type === 6) {
              customFieldRenderFileData.value.push({
                name: fieldVal.name,
                values: fieldVal.optVos
                  .filter((optVo) => !!optVo.optValue)
                  .map((optVo) => optVo.optValue),
              })
            }
          })
        })
      }
    },
    { deep: true, immediate: true },
  )
</script>

<template>
  <div>
    <span @click="modalVisible = true">
      <slot></slot>
    </span>

    <HModal @close="onClose" v-model="modalVisible" title="审核结单" width="auto">
      <div
        class="modal_body"
        v-loading="getWaitCheckStatementOrderLoading || checkStatementOrderLoading"
      >
        <div class="title">
          <div class="color_column"></div>
          <div class="text">基本信息</div>
        </div>

        <el-form v-if="waitCheckStatementOrderInfo">
          <div class="form_content">
            <el-form-item label="工单单号:">
              <span style="font-size: 12px; color: #000">{{ props.wordNo }}</span>
            </el-form-item>
            <el-form-item label="申请人员:">
              <span style="font-size: 12px; color: #000">{{
                waitCheckStatementOrderInfo.applyEmp
              }}</span>
            </el-form-item>
            <el-form-item label="申请时间:">
              <span style="font-size: 12px; color: #000">{{
                waitCheckStatementOrderInfo.applyTime
              }}</span>
            </el-form-item>
            <!--自定义字段（文本类）-->
            <el-form-item
              v-for="(customField, customFieldIndex) in customFieldRenderTextData"
              :key="customFieldIndex"
              :label="`${customField.name}:`"
            >
              <span style="font-size: 12px; color: #000">{{ customField.values.join('，') }}</span>
            </el-form-item>
            <el-form-item
              v-for="(customField, customFieldIndex) in customFieldRenderRateData"
              :key="customFieldIndex"
              :label="`${customField.name}:`"
            >
              <!-- 评分 -->
              <el-rate disabled allow-half :model-value="Number(customField.values / 2)" />
              <span>{{ Number(customField.values) }}</span>
            </el-form-item>
          </div>
        </el-form>

        <!--自定义字段（图片类）-->
        <el-form v-if="waitCheckStatementOrderInfo">
          <div class="form_content">
            <el-form-item
              v-for="(customField, customFieldIndex) in customFieldRenderImageData"
              :key="customFieldIndex"
              :label="`${customField.name}:`"
            >
              <el-scrollbar
                height="50px"
                style="max-width: 280px"
                always
                v-if="customField.values.length > 0"
              >
                <div class="image_container">
                  <div
                    class="img"
                    v-for="(customFieldImage, customFieldImageIndex) in customField.values"
                    :key="customFieldImageIndex"
                  >
                    <el-image
                      class="img"
                      :src="customFieldImage"
                      fit="scale-down"
                      :preview-src-list="customField.values"
                      :initial-index="customFieldImageIndex"
                      preview-teleported
                    />
                  </div>
                </div>
              </el-scrollbar>
              <span v-else>-</span>
            </el-form-item>
          </div>
        </el-form>

        <!--自定义字段（附件类）-->
        <el-form v-if="waitCheckStatementOrderInfo" style="margin-bottom: 12px">
          <div class="form_content">
            <el-form-item
              v-for="(customField, customFieldIndex) in customFieldRenderFileData"
              :key="customFieldIndex"
              :label="`${customField.name}:`"
            >
              <el-scrollbar
                height="50px"
                style="max-width: 280px"
                always
                v-if="customField.values.length > 0"
              >
                <div class="file_container">
                  <div
                    class="file"
                    v-for="(customFieldImage, customFieldImageIndex) in customField.values"
                    :key="customFieldImageIndex"
                  >
                    <el-image class="file" :src="pdf" fit="scale-down" />
                    <div class="view" @click="handlePreviewFile(customFieldImageIndex)">
                      <el-icon color="#fff" size="18" style="cursor: pointer">
                        <View />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
              <span v-else>-</span>
            </el-form-item>
          </div>
        </el-form>

        <!--自定义字段（视频类）-->
        <el-form v-if="waitCheckStatementOrderInfo">
          <div class="form_content">
            <el-form-item
              v-for="(customField, customFieldIndex) in customFieldRenderVideoData"
              :key="customFieldIndex"
              :label="`${customField.name}:`"
            >
              <el-scrollbar
                height="50px"
                style="max-width: 280px"
                always
                v-if="customField.values.length > 0"
              >
                <div class="video_container">
                  <div
                    class="video"
                    v-for="(customFieldVideo, customFieldVideoIndex) in customField.values"
                    :key="customFieldVideoIndex"
                  >
                    <video width="70" height="35" :src="customFieldVideo"></video>
                    <div
                      class="view"
                      @click="handlePreviewVideo(customField.values, customFieldVideoIndex)"
                    >
                      <el-icon color="#fff" size="18" style="cursor: pointer">
                        <View />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
              <span v-else>-</span>
            </el-form-item>
          </div>
        </el-form>
        <el-form>
          <el-form-item label="审核备注:">
            <el-input
              maxlength="200"
              v-model="form.remark"
              show-word-limit
              type="textarea"
              placeholder="请填写备注"
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footerLeft>
        <HPlainBgButton
          type="error"
          is-modal
          :loading="checkStatementOrderLoading"
          @click="onRejectBtnClick"
          >驳回
        </HPlainBgButton>
      </template>
      <template #footerRight>
        <HButton
          type="primary"
          is-modal
          :loading="checkStatementOrderLoading"
          @click="onSubmitBtnClick"
          >通过
        </HButton>
        <HButton isModal @click="onClose">取消</HButton>
      </template>
    </HModal>

    <!--视频预览弹窗-->
    <HModal @close="onCloseVideoPreviewModal" v-model="videoPreviewModalVisible" title="视频预览">
      <div style="display: flex; align-items: center; gap: 12px; justify-content: center">
        <el-button
          type="primary"
          :disabled="videoPreviewIndex === 0"
          @click="videoPreviewIndex--"
          :icon="ArrowLeftBold"
          style="padding: 0 14px"
        />
        <video :src="videoPreviewUrls[videoPreviewIndex]" controls width="500"></video>
        <el-button
          type="primary"
          :disabled="videoPreviewIndex === videoPreviewUrls.length - 1"
          @click="videoPreviewIndex++"
          :icon="ArrowRightBold"
          style="padding: 0 14px"
        />
      </div>
    </HModal>

    <!--附件预览弹窗-->
    <HModal @close="onCloseFilePreviewModal" v-model="filePreviewModalVisible" title="附件">
      <div style="display: flex; align-items: center; gap: 12px; justify-content: center">
        <el-button
          type="primary"
          :disabled="filePreviewIndex === 0"
          @click="filePreviewIndex--"
          :icon="ArrowLeftBold"
          style="padding: 0 14px"
        />
        <iframe :src="filePreviewUrls[filePreviewIndex]" style="width: 100%; height: 78vh"></iframe>
        <el-button
          type="primary"
          :disabled="filePreviewIndex === filePreviewUrls.length - 1"
          @click="filePreviewIndex++"
          :icon="ArrowRightBold"
          style="padding: 0 14px"
        />
      </div>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  :deep(.el-textarea) {
    .el-textarea__inner {
      max-height: 190px;
      min-height: 50px !important;
      min-width: 300px;
      max-width: 400px;
      overflow: hidden;
    }
  }

  :deep(.el-form-item__label) {
    font-size: 12px;
    color: #6c6e72;
  }

  :deep(.el-textarea__inner) {
    resize: none;
  }

  .modal_body {
    .title {
      display: flex;
      gap: 5px;
      align-items: center;

      .color_column {
        width: 2px;
        height: 15px;
        border-radius: 2px;
        background-color: $primaryColor;
      }

      .text {
        color: #000;
      }
    }

    .form_content {
      display: grid;
      grid-template-columns: repeat(1, 1fr);

      .image_container {
        display: flex;
        gap: 10px;
        flex-direction: row;

        .img {
          width: 35px;
          height: 35px;
          border-radius: 2px;
          cursor: pointer;
        }
      }

      .video_container {
        display: flex;
        gap: 10px;
        flex-direction: row;

        .video {
          width: 70px;
          height: 35px;
          border-radius: 2px;
          cursor: pointer;
          position: relative;

          .view {
            position: absolute;
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            background-color: rgba(#000, 0.4);
            top: 0;
            left: 0;
            opacity: 0;
            transition: all 0.3s ease-in-out;
            cursor: pointer;
          }

          &:hover {
            .view {
              opacity: 1;
            }
          }
        }
      }

      .file_container {
        display: flex;
        gap: 10px;
        flex-direction: row;
        .file {
          width: 35px;
          height: 35px;
          border-radius: 2px;
          cursor: pointer;
          position: relative;

          .view {
            position: absolute;
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            background-color: rgba(#000, 0.4);
            top: 0;
            left: 0;
            opacity: 0;
            transition: all 0.3s ease-in-out;
            cursor: pointer;
          }

          &:hover {
            .view {
              opacity: 1;
            }
          }
        }
      }
    }
  }

  .footer_btn_group {
    display: flex;
    gap: 10px;
    justify-content: space-between;
  }
</style>
